package com.gaff.emp.core.config;

import com.gaff.emp.core.config.extend.EmpInterceptorRegistry;
import com.gaff.emp.core.modules.auth.interceptor.AuthorizationInterceptor;
import com.gaff.emp.core.modules.auth.resolver.UserInfoHandlerMethodArgumentResolver;
import com.gaff.emp.core.util.ContextUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.*;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import java.io.File;
import java.util.List;

@Configuration
@Slf4j
public class WebMvcConfig implements WebMvcConfigurer {

    @Value("${gaff.welcome.page:index.html}")
    private String welcomePage;

    @Autowired
    private UserInfoHandlerMethodArgumentResolver userInfoHandlerMethodArgumentResolver;

    @Autowired
    private EmpInterceptorRegistry empInterceptorRegistry;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        for (HandlerInterceptorAdapter interceptor : empInterceptorRegistry.getInterceptors()) {
            registry.addInterceptor(interceptor).addPathPatterns("/**");
        }
    }

    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
        argumentResolvers.add(userInfoHandlerMethodArgumentResolver);
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        String staticDir = ContextUtil.getRootPath() + File.separator + "static" + File.separator;
        log.info("resource dir = " + staticDir);
        registry.addResourceHandler("/**").addResourceLocations("file:" + staticDir);
        registry.addResourceHandler("/swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
    }

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("redirect:/" + welcomePage);
        registry.setOrder(Ordered.HIGHEST_PRECEDENCE);
    }

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowCredentials(true)
                .allowedMethods("*")
                .allowedHeaders("*")
                .maxAge(3600);
    }
}
